<template>
  <div class="right-map">
    <div id="container" ref="mapContainer"></div>
    <div class="emergency-title">
      <div class="emergency-title-txt">消防水务应急管理系统</div>
      <div class="slope"></div>
    </div>
    <div class="list-box">
      <div class="risk-box" :style="{color:sensor.color}">
        <img :src="sensor.img" alt="">
        <span class="item-name">{{sensor.name}}</span>
        <span>{{sensor.num}}</span>
      </div>
      <div class="risk-box" style="{color:cinema.color}">
        <img :src="cinema.img" alt="">
        <span class="item-name">{{cinema.name}}</span>
        <span>{{cinema.num}}</span>
      </div>
    </div>
    <div class="insure-box">
      <div class="each-insure" @click="openWarn">
        <img src="./images/icon5.png" alt="">
        <span class="warn-txt">告警消息</span>
        <div class="warn-msg" v-if="warnBox">
          <span class="warn-title">预警信息</span>

          <el-scrollbar class="warn-box">
            <div class="each-warn" v-for="item in warnList">
              <img src="./images/icon3.png" alt="">
              <div class="warn-info"><span class="time">{{item.time}}</span><span
                class="detail">{{item.detail}}</span></div>
            </div>
          </el-scrollbar>
        </div>
      </div>
      <div class="each-insure">
        <div class="insure-text" :style="{color:inline.color,borderBottomColor:inline.borderColor}">
          {{inline.name}}
        </div>
        <div class="insure-num" :style="{backgroundColor:inline.bgColor}">
          <text class="num">{{inline.num}}</text>
        </div>
      </div>
      <div class="each-insure">
        <div class="insure-text" :style="{color:offline.color,borderBottomColor:offline.borderColor}">
          {{offline.name}}
        </div>
        <div class="insure-num" :style="{backgroundColor:offline.bgColor}">
          <text class="num">{{offline.num}}</text>
        </div>
      </div>
      <div class="weather">
        <img src="./images/icon2.png" alt="">
        <div class="weather-info">
          <div class="today-weather"><span>今晴11~20℃</span> <span class="grade">优</span></div>
          <div>明多云13～22℃</div>
        </div>
      </div>
    </div>
    <div class="alarm-pop" v-if="ifShowAlarmPop">
      <img src="./images/icon_close.png" class="icon-close" @click="closeAlarmPop"><span class="pop-warn-title">{{popMsg.title}}</span>
      <div class="alarm-pop-video">
        <img src="./images/alarm_pop_img.png" class="alarm-pop-img">
        <div class="alarm-pop-alarm"><span> </span><span>{{popMsg.msg}}</span><img src="./images/icon_full.png"
                                                                                   @click="goFullscreen">
        </div>
      </div>
    </div>
    <!--        全屏-->
    <div class="pop-fullscreen" v-if="fullShowAlarmPop">
      <img src="./images/alarm_pop_img.png" class="pop-fullscreen-img">
      <div class="alarm-pop-alarm"><span> </span><span>{{popMsg.msg}}</span><img
        src="./images/exit-fullscreen.png"
        style="width: 32px;height: 32px" @click="exitFullscreen">
      </div>
    </div>
    <img src="./images/icon7.png" class="warn-img" v-if="ifShowImg">
    <div style="width:600px;height:400px;z-index: 9999;position: absolute;top: 100px;left: 300px;">
      <div id="video-container" style="width:100%;height: 100%;"></div>
    </div>
  </div>
</template>

<script type="text/ecmascript-6">
  import mapStyle from './custom_map_config.json'
  import EZUIKit from 'ezuikit-js'
  import { getCinemaAccessToken, screenDeviceDistribution } from '@/api/index'
  import loadAMap from '@/utils/loadMap'

  export default {
    name: 'index',
    components: {},
    data() {
      return {
        map: null,
        labelsLayer: null, //LabelsLayer 图层是承载 LabelMarker 的图层
        player: null,
        accessToken: null,
        deviceList: [],
        markLabelsData:[],
        sensor: {
          img: '/src/views/images/icon8.png',
          name: '传感器',
          type: '001',
          num: '100',
          color: '#1bf70a'
        },
        cinema: {
          img: '/src/views/images/icon9.png',
          name: '摄像头',
          num: '20',
          color: '#f7260a'
        },

        inline: { name: '在线设备', num: '86', color: '#1bf70a', borderColor: '#097E5E', bgColor: '#097E5E' },
        offline: { name: '离线设备', num: '86', color: '#BA9F30', borderColor: '#C0A32E', bgColor: '#C0A32E' },
        insureList: [
          { name: '在线设备', num: '86', color: '#1bf70a', borderColor: '#097E5E', bgColor: '#097E5E' },
          { name: '离线设备', num: '86', color: '#BA9F30', borderColor: '#C0A32E', bgColor: '#C0A32E' }
        ],
        mapStyle: {
          styleJson: mapStyle
        },
        ifShowImg: false,
        warnBox: false,
        warnList: [],
        ifShowAlarmPop: false,
        //告警提醒或监控设备
        popMsg: {
          title: '告警提醒',
          msg: '东涌水位过高'
        },
        fullShowAlarmPop: false,
        buMap: null
      }
    },
    methods: {
      async initMap() {
        this.locateDevices = this.deviceList.filter(it => {
          if (it.longitude && it.latitude) {
            return it
          }
        })
        const AMap = await loadAMap()
        this.map = new AMap.Map(this.$refs.mapContainer, {
          resizeEnable: true,
          zoom: 16, //初始化地图级别
          showIndoorMap: false,
          center: this.locateDevices.length ? [this.locateDevices[0].longitude, this.locateDevices[0].latitude] : [116.405467, 39.907761] //初始化地图中心点位置
        })
        AMap.plugin(['AMap.Scale', 'AMap.ToolBar', 'AMap.ControlBar'], () => {
          const Scale = new AMap.Scale()
          const toolBar = new AMap.ToolBar({
            position: 'RB',
            offset: new AMap.Pixel(150, 220)
          })
          const controlBar = new AMap.ControlBar()
          // const geolocation = new AMap.Geolocation({
          //   // 是否使用高精度定位，默认：true
          //   enableHighAccuracy: true,
          //   // 设置定位超时时间，默认：无穷大
          //   timeout: 10000,
          //   // 定位按钮的停靠位置的偏移量
          //   offset: [20, 100],
          //   //  定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
          //   zoomToAccuracy: true,
          //   //  定位按钮的排放位置,  RB表示右下
          //   position: "RB",
          // });
          this.map.addControl(controlBar)
          this.map.addControl(toolBar)
          this.map.addControl(Scale)
        })
        setTimeout(() => {
          this.placeSearch();
          this.deviceMark2Map();
        }, 100)
      },
      placeSearch(){
        let _that=this;
        var searchParams;

        AMap.plugin('AMap.CitySearch', function () {
          var citySearch = new AMap.CitySearch()
          citySearch.getLocalCity(function (status, result) {
            if (status === 'complete' && result.info === 'OK') {
              // 查询成功，result即为当前所在城市信息
              debugger;
              searchParams=result;
              searchParams.map=_that.map;
              searchParams.autoFitView=true;
              console.log(result);
            }
          })
        })
        AMap.plugin(["AMap.PlaceSearch"], function() {
          //构造地点查询类
          var placeSearch = new AMap.PlaceSearch(searchParams);

          var cpoint = [113.370718, 22.513888]; //中心点坐标
          placeSearch.search('广州', function(status, result) {
            debugger;
            // 查询成功时，result即对应匹配的POI信息
            console.log(result)
            var pois = result.poiList.pois;
            for(var i = 0; i < pois.length; i++){
              var poi = pois[i];
              var marker = [];
              marker[i] = new AMap.Marker({
                position: poi.location,   // 经纬度对象，也可以是经纬度构成的一维数组[116.39, 39.9]
                title: poi.name
              });
              // 将创建的点标记添加到已有的地图实例：
              map.add(marker[i]);
            }
            map.setFitView();
          });
        });
      },
      deviceMark2Map(status, playStatus, zoomLevel) {
        var _that=this;
        if (this.mapMarks && this.mapMarks.length) {
          this.mapMarks.forEach(marker => {
            this.map.remove(marker)
          })
        }
        var textStyle = {
          fontSize: 12,
          fontWeight: 'normal',
          fillColor: '#22886f',
          strokeColor: '#fff',
          strokeWidth: 2,
          fold: true,
          padding: '2, 5',
        };


        this.mapMarks = []
        var i=0;
        this.locateDevices.forEach((it) => {
          if (it.status == undefined) it.status = '1'
          if (status && it.status !== status) {
            return false
          }
          if (playStatus && it.playStatus !== playStatus) {
            return false
          }
          const pointer = [it.longitude, it.latitude]
          var itemJson={};
          itemJson.name=it.name;
          itemJson.text= {content: it.name,direction: 'right',offset: [-20, -5],style: textStyle}
          itemJson.icon={
            type: 'image',
            image: it.status == '0' ? require('@/assets/images/' + it.type + '-off.png') : require('@/assets/images/' + it.type + '-on.png'),
            // 图片相对 position 的锚点，默认为 bottom-center
            anchor: 'center',
          }

          itemJson.zIndex=i;
          itemJson.opacity=1;
          itemJson.zooms=[10, 20];
          itemJson.position=pointer;
          itemJson.data=it;
          itemJson.offset=new AMap.Pixel(10, -27);
          _that.markLabelsData.push(itemJson);

/*          var marker = new AMap.Marker({
            // "https://webapi.amap.com/theme/v1.3/markers/n/mark_b.png"
            icon: it.status == '0'
              ? require('@/assets/images/' + it.type + '-off.png')
              : require('@/assets/images/' + it.type + '-on.png'),
            offset: new AMap.Pixel(10, -27),
            data: it,
            position: pointer
          })

          this.mapMarks.push(marker)
          // 单独将点标记添加到地图上
          this.map.add(marker)*/
          if (this.mapMarks.length === 1) {
            this.map.setZoomAndCenter(zoomLevel || 16, pointer)
          }
          i++;
        })

        var markers = [];
        var allowCollision = false;
        var layer = new AMap.LabelsLayer({
          zooms: [3, 20],
          zIndex: 1000,
          // collision: false,
          // 设置 allowCollision：true，可以让标注避让用户的标注
          allowCollision,
        });
// 初始化 labelMarker
        for (var i = 0; i < _that.markLabelsData.length; i++) {
          var curData = _that.markLabelsData[i];
          curData.extData = {
            index: i
          };
          var labelMarker = new AMap.LabelMarker(curData);
          labelMarker.on('click', (e) => {
            debugger;
            console.log(e.target._opts.data)
            debugger
            if (e.target._opts.data.type == 'camera') {
              this.playCamera(e.target._opts.data.code)
            } else {
              this.openDevInfoWindow(e.target._opts.data) // 弹窗弹出})
            }
            // console.log(obj)
            this.currentInfoData = e.target._opts.data
            this.infoWindowDialogVisible = true
          })
          markers.push(labelMarker);
        }
        // 将 marker 添加到图层
        layer.add(markers);
        // 图层添加到地图
        _that.map.add(layer);
        _that.map.setFitView(null, false, [100, 150, 10,10]);
      },
      openDevInfoWindow(devInfo) {
        //在指定位置打开信息窗体
        //构建信息窗体中显示的内容
        var info = []
        info.push('<div class=\'input-card content-window-card\'>')
        info.push('<div style="padding:7px 0px 0px 0px;"><h4>设备信息</h4>')
        info.push('<p class=\'input-item\'>设备名称: ' + devInfo.name + '</p>')
        info.push('<p class=\'input-item\'>设备编码: ' + devInfo.code + '</p></div></div>')

        var infoWindow = new AMap.InfoWindow({
          content: info.join('')  //使用默认信息窗体框样式，显示信息内容
        })

        infoWindow.open(this.map, this.map.getCenter())
      },
      openWarn() {
        let that = this
        that.warnBox = !that.warnBox
      },
      getWarnList() {
        // debugger
        var that = this
        var newList = []
        for (let i = 0; i < 25; i++) {
          newList.push({
            id: i,
            time: '2022-09-10 02:10:' + (i > 9 ? i : '0' + i),
            detail: '三星水产生产有限公司水质PH值过高'
          })
        }
        that.warnList = newList
        console.log(that.warnList)
      },
      closeAlarmPop() {
        let that = this
        that.ifShowAlarmPop = false
        that.ifShowImg = false
      },
      goFullscreen() {
        this.fullShowAlarmPop = true
      },
      exitFullscreen() {
        this.fullShowAlarmPop = false
      },
      getAccessToken() {
        getCinemaAccessToken().then(res => {
          this.accessToken = res.data
        })
      },
      playCamera(serial) {
        var info = []
        info.push('<div class=\'input-card content-window-card\'><div id=\'camera-play-view\'></div></div>')

        var infoWindow = new AMap.InfoWindow({
          content: info.join('')  //使用默认信息窗体框样式，显示信息内容
        })
        //在指定位置打开信息窗体
        //构建信息窗体中显示的内容
        infoWindow.open(this.map, this.map.getCenter())

        debugger;
        this.player = new EZUIKit.EZUIKitPlayer({
          id: 'camera-play-view', // 视频容器ID
          accessToken: this.accessToken,
          url: 'ezopen://open.ys7.com/' + serial + '/1.hd.live'
        })

        this.player.play()
      },
      stopCamera() {
        if (this.player != null) {
          this.player.stop()
          this.player = null
        }
      },
      screenDeviceDistribution() {
        screenDeviceDistribution().then(res => {
          this.deviceList = res.data.result
          this.sensor.num = res.data.sensor
          this.cinema.num = res.data.cinema
          this.inline.num = res.data.inline
          this.offline.num = res.data.offline
          this.initMap()
        })
      }
    },
    mounted() {
      // this.getWarnList()
      this.getAccessToken()
      this.screenDeviceDistribution()
    }
  }
</script>

<style scoped lang="scss">

  .right-map {
    width: 100%;
    height: 100%;
    font-size: 20px;
    box-sizing: border-box;
    position: relative;
  }

  .emergency-title {
    line-height: 60px;
    margin-bottom: 20px;
    font-size: 24px;
    text-align: center;
    position: absolute;
    top: 0;
    left: 0;
    color: #1de4fc;
    display: flex;
    align-items: center;
  }

  .emergency-title-txt {
    width: 400px;
    height: 60px;
    white-space: nowrap;
    background-color: rgba(24, 87, 159, 0.75);
  }

  .slope {
    width: 60px;
    height: 60px;
    transform: skewX(-45deg);
    background-color: rgba(24, 87, 159, 0.75);
    position: absolute;
    left: 370px;
  }

  .warn-img {
    position: absolute;
    bottom: 30px;
    right: 60px;
  }

  .warn-msg {
    width: 500px;
    height: 250px;
    box-sizing: border-box;
    background: url("./images/right_border.png") no-repeat;
    background-size: 100% 100%;
    position: absolute;
    top: 50px;
  }

  .warn-box {
    width: 100%;
    height: 100%;
    padding: 10px 20px;
    box-sizing: border-box;
    overflow-y: auto;
    position: relative;
  }

  .warn-box:hover {
    z-index: 2;
  }

  .warn-title {
    writing-mode: vertical-rl;
    color: #19b7d9;
    position: absolute;
    right: 1px;
    top: 10%;
  }

  .each-warn {
    width: 100%;
    line-height: 40px;
    display: flex;
    align-items: center;
  }

  .each-warn:hover {
  }

  .warn-info {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    color: #f7260a;
  }

  .warn-info:hover {
    font-weight: bold;
  }

  .time {
    color: #dee1e1;
    margin: 0 10px;
  }

  .detail {
    color: #f7260a;
  }

  .list-box {
    position: absolute;
    top: 80px;
    left: 20px;
  }

  .warn-txt {
    color: #f2cf0e;
    white-space: nowrap;
  }

  .risk-box {
    line-height: 30px;
  }

  .item-name {
    margin: 0 10px;
  }

  .insure-box {
    position: absolute;
    right: 20px;
    top: 20px;
    display: flex;
    align-items: center;
    z-index: 99;
  }

  .each-insure {
    padding: 0 10px;
    display: flex;
    align-items: center;
    position: relative;
  }

  .insure-text {
    line-height: 29px;
    text-align: center;
    box-sizing: border-box;
    color: #1bf70a;
    border-bottom: 1px solid;
    white-space: nowrap;
    padding: 0 10px;
  }

  .insure-num {
    width: 40px;
    height: 30px;
    line-height: 30px;
    text-align: center;
    transform: skewX(-15deg);
    color: #dddfdd;
  }

  .num {
    display: block;
    transform: skewX(15deg);
  }

  #container {
    width: 100%;
    height: 100%;
    /*border-radius: 10px;*/
    box-shadow: 0px 0px 20px #000023ff;
  }

  .weather {
    padding: 0 10px;
    box-sizing: border-box;
    display: flex;
    align-items: center;
    justify-content: right;
  }

  .weather-info {
    margin-left: 10px;
    font-family: AdobeHeitiStd-Regular;
    color: #bec0c0;
  }

  .today-weather {
    margin-bottom: 5px;
  }

  .grade {
    padding: 1px 15px;
    background-color: #05a77b;
    border-radius: 10px;
  }

  /*去掉百度地图的logo等*/
  // ::v-deep(.anchorBL) {
  //     display: none !important;
  // }

  .alarm-pop {
    width: 50%;
    height: 60%;
    box-sizing: border-box;
    background: url("./images/right_border.png") no-repeat;
    background-size: 100% 100%;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    z-index: 99;
  }

  .pop-warn-title {
    writing-mode: vertical-rl;
    letter-spacing: 6px;
    color: #f6ad20;
    position: absolute;
    right: 15px;
    top: 20%;
    font-size: 24px;
  }

  .icon-close {
    position: absolute;
    top: 15px;
    right: 15px;
  }

  .alarm-pop-video {
    width: 85%;
    height: calc(100% - 60px);
    box-sizing: border-box;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
  }

  .alarm-pop-img {
    width: 100%;
    height: calc(100% - 60px);
  }

  .alarm-pop-alarm {
    width: 100%;
    height: 60px;
    box-sizing: border-box;
    padding: 0 20px;
    position: absolute;
    bottom: 0;
    left: 50%;
    transform: translateX(-50%);
    display: flex;
    align-items: center;
    justify-content: space-between;
    color: #f92616;
    background-color: #2a2b2a;
    font-size: 24px;
  }

  .pop-fullscreen {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    box-sizing: border-box;
    z-index: 100;
  }

  .pop-fullscreen-img {
    width: 100%;
    height: 100%;
  }

  .input-card {
    font-size: 14px;
  }

  #camera-play-view {
    width: 680px;
    height: 520px;
  }

  // /*    点击标志的弹窗*/
  // ::v-deep(.BMap_bubble_pop) {
  //     width: 400px !important;
  //     border: 0 !important;
  //     background: url("./images/right_border.png") no-repeat !important;
  //     background-size: 100% 100% !important;
  //     box-sizing: border-box !important;
  // }

  // ::v-deep(.BMap_bubble_center) {
  //     width: 100% !important;
  //     box-sizing: border-box !important;
  // }

  // ::v-deep(.BMap_bubble_content) {
  //     width: 100% !important;
  //     overflow-y: auto !important;
  //     box-sizing: border-box !important;
  // }

  // ::v-deep(.pb-20) {
  //     width: 100% !important;
  //     min-height: 150px !important;
  //     max-height: 200px !important;
  //     overflow-y: auto !important;
  //     color: #ffffff !important;
  //     box-sizing: border-box !important;
  // }

  // /*去除阴影*/
  // ::v-deep(.shadow img ) {
  //     display: none !important;
  // }

</style>
